﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Web.Host.Models
{
    public class WebApiModel
    {
        #region Public Members

        public IEnumerable<string> Resources { get; set; }
        public IEnumerable<string> Actions { get; set; }
        public Sidvall.Security.ResourceItemCollection ResourceItems { get; set; }

        #region GetResult

        public Sidvall.Security.ResourceItem GetResult(string resource, string action)
        {
            var items = this.ResourceItems.FindItems(resource, action);
            return Sidvall.Security.ResourceItem.CreateResourceItem(items, Sidvall.Security.ResourceItemAccessLevel.None, "<br/>", true);
        }

        #endregion
        #region LoadAsync

        public async Task LoadAsync()
        {
            var resourceActions = Sidvall.WorkItemManager.Web.SystemContext.Current.ControllerManager.GetResourceItems(Startup.HttpConfiguration.Routes);
            this.Resources = (from o in resourceActions
                              orderby o.Resource
                              select o.Resource).Distinct();
            this.Actions = (from o in resourceActions
                            orderby o.Action
                            select o.Action).Distinct();
            this.ResourceItems = await Sidvall.SystemContext.Current.AuthorizationManager.GetSystemResourceItemsAsync();
        }

        #endregion

        #endregion
        #region Constructors

        public WebApiModel()
        {
        }

        #endregion
    }
}